﻿#ifndef __SS_MYSQL_CONNECTION_H__
#define __SS_MYSQL_CONNECTION_H__
#include "../ssMySQLDefin.h"
#include "container/ssMultiLineBuffer.h"
#include "byteStream/ssWriteBytes.h"
#include <string>

namespace StarSeeker
{

class ssMySQLConnection
{
	friend class ssMySQLStmt;
	friend class ssMySQLPool;
public:
	ssMySQLConnection();
	virtual ~ssMySQLConnection();
	//初始化连接
	bool Init(const char *pIP, u32	port, const char *pAccount, const char *pPW, const char *pDBName);
	//结束连接
	void Exit();
	//设置字符集
	void SetCharacter(const char *pc);
	//设置数据库
	void SelectDB(const char *pDBName);
	//执行语句不返回数据
	bool Execute(const char *sql);
	//查询语句并返回数据
	//bool Query(const char *sql);
	//开始事务
	bool Transaction();
	//提交事务
	bool Commit();
	//回滚事务
	bool Rollback();
	//获取结果
	ssWriteBytes& GetOneResult() { return m_result; }
	//获取结果集
	ssMultiLineBuffer& GetResultSet() { return m_resultSet; }
	//清理缓存
	void CleanBuffer();
	//清空结果缓冲区
	void ClearResult();
	//获取查询的行数
	u64 GetAffectedRows() { return m_affectedRows; }
	//获取新插入的ID
	u64 GetInsertID() { return m_insertID; }
	//获取结果行数
	ulint GetRows() { return m_resultSet.Count(); }
	//获取错误信息
	const std::string& ErrorInfo() { return m_error; }
protected:
	//重新预处理
	virtual void RePrepare();
	//连接数据库
	bool Connect();
	//错误检测
	void CheckError(const char * str);

	MYSQL*			m_pConnect;
	std::string		m_IP;
	u32				m_port;
	std::string		m_account;
	std::string		m_password;
	std::string		m_name;
	std::string		m_character;
	std::string		m_serverVersion;
	std::string		m_clientVersion;

	u64					m_affectedRows;
	u64					m_insertID;
	ssWriteBytes		m_result;		//一个结果集
	ssMultiLineBuffer	m_resultSet;	//多个结果集
public:
	u32					m_errno;
	std::string			m_error;
	bool				m_free;
};

}
#endif
